Class yii\db\ActiveQuery
Inheritance | yii\db\ActiveQuery » yii\db\Query » yii\base\Component » yii\base\Object |
---|---|
Implements | yii\base\Configurable, yii\db\ActiveQueryInterface, yii\db\QueryInterface |
Uses Traits | yii\db\ActiveQueryTrait, yii\db\ActiveRelationTrait, yii\db\QueryTrait |
Subclasses | spinitron\dynamicAr\DynamicActiveQuery, tests\unit\data\CustomerQuery |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveQuery.php |
ActiveQuery represents a DB query associated with an Active Record class.
An ActiveQuery can be a normal query or be used in a relational context.
ActiveQuery instances are usually created by yii\db\ActiveRecord::find() and yii\db\ActiveRecord::findBySql(). Relational queries are created by yii\db\ActiveRecord::hasOne() and yii\db\ActiveRecord::hasMany().
Normal Query ¶
ActiveQuery mainly provides the following methods to retrieve the query results:
- one(): returns a single record populated with the first row of data.
- all(): returns all records based on the query results.
- count(): returns the number of records.
- sum(): returns the sum over the specified column.
- average(): returns the average over the specified column.
- min(): returns the min over the specified column.
- max(): returns the max over the specified column.
- scalar(): returns the value of the first column in the first row of the query result.
- column(): returns the value of the first column in the query result.
- exists(): returns a value indicating whether the query result has data or not.
Because ActiveQuery extends from yii\db\Query, one can use query methods, such as where(), orderBy() to customize the query options.
ActiveQuery also provides the following additional query options:
- with(): list of relations that this query should be performed with.
- indexBy(): the name of the column by which the query result should be indexed.
- asArray(): whether to return each record as an array.
These options can be configured using methods of the same name. For example:
$customers = Customer::find()->with('orders')->asArray()->all();
Relational query ¶
In relational context ActiveQuery represents a relation between two Active Record classes.
Relational ActiveQuery instances are usually created by calling yii\db\ActiveRecord::hasOne() and yii\db\ActiveRecord::hasMany(). An Active Record class declares a relation by defining a getter method which calls one of the above methods and returns the created ActiveQuery object.
A relation is specified by $link which represents the association between columns of different tables; and the multiplicity of the relation is indicated by $multiple.
If a relation involves a junction table, it may be specified by via() or viaTable() method. These methods may only be called in a relational context. Same is true for inverseOf(), which marks a relation as inverse of another relation and onCondition() which adds a condition that is to be added to relational query join condition.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$asArray | boolean | Whether to return each record as an array. | yii\db\ActiveQueryTrait |
$behaviors | \yii\base\Behavior[] | List of behaviors attached to this component | yii\base\Component |
$distinct | boolean | Whether to select distinct rows of data only. | yii\db\Query |
$from | array | The table(s) to be selected from. | yii\db\Query |
$groupBy | array | How to group the query results. | yii\db\Query |
$having | string|array | The condition to be applied in the GROUP BY clause. | yii\db\Query |
$indexBy | string|callable | The name of the column by which the query results should be indexed by. | yii\db\QueryTrait |
$inverseOf | string | The name of the relation that is the inverse of this relation. | yii\db\ActiveRelationTrait |
$join | array | How to join with other tables. | yii\db\Query |
$joinWith | array | A list of relations that this query should be joined with | yii\db\ActiveQuery |
$limit | integer | Maximum number of records to be returned. | yii\db\QueryTrait |
$link | array | The columns of the primary and foreign tables that establish a relation. | yii\db\ActiveRelationTrait |
$modelClass | string | The name of the ActiveRecord class. | yii\db\ActiveQueryTrait |
$multiple | boolean | Whether this query represents a relation to more than one record. | yii\db\ActiveRelationTrait |
$offset | integer | Zero-based offset from where the records are to be returned. | yii\db\QueryTrait |
$on | string|array | The join condition to be used when this query is used in a relational context. | yii\db\ActiveQuery |
$orderBy | array | How to sort the query results. | yii\db\QueryTrait |
$params | array | List of query parameter values indexed by parameter placeholders. | yii\db\Query |
$primaryModel | yii\db\ActiveRecord | The primary model of a relational query. | yii\db\ActiveRelationTrait |
$select | array | The columns being selected. | yii\db\Query |
$selectOption | string | Additional option that should be appended to the 'SELECT' keyword. | yii\db\Query |
$sql | string | The SQL statement to be executed for retrieving AR records. | yii\db\ActiveQuery |
$union | array | This is used to construct the UNION clause(s) in a SQL statement. | yii\db\Query |
$via | array|object | The query associated with the junction table. | yii\db\ActiveRelationTrait |
$where | string|array | Query condition. | yii\db\QueryTrait |
$with | array | A list of relations that this query should be performed with | yii\db\ActiveQueryTrait |
Public Methods
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | yii\base\Component |
__clone() | Clones internal objects. | yii\db\ActiveRelationTrait |
__construct() | Constructor. | yii\db\ActiveQuery |
__get() | Returns the value of a component property. | yii\base\Component |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\base\Component |
__set() | Sets the value of a component property. | yii\base\Component |
__unset() | Sets a component property to be null. | yii\base\Component |
addGroupBy() | Adds additional group-by columns to the existing ones. | yii\db\Query |
addOrderBy() | Adds additional ORDER BY columns to the query. | yii\db\QueryTrait |
addParams() | Adds additional parameters to be bound to the query. | yii\db\Query |
addSelect() | Add more columns to the SELECT part of the query. | yii\db\Query |
all() | Executes query and returns all results as an array. | yii\db\ActiveQuery |
andFilterWhere() | Adds an additional WHERE condition to the existing one but ignores empty operands. | yii\db\QueryTrait |
andHaving() | Adds an additional HAVING condition to the existing one. | yii\db\Query |
andOnCondition() | Adds an additional ON condition to the existing one. | yii\db\ActiveQuery |
andWhere() | Adds an additional WHERE condition to the existing one. | yii\db\QueryTrait |
asArray() | Sets the asArray() property. | yii\db\ActiveQueryTrait |
attachBehavior() | Attaches a behavior to this component. | yii\base\Component |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\base\Component |
average() | Returns the average of the specified column values. | yii\db\Query |
batch() | Starts a batch query. | yii\db\Query |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\base\Component |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\base\Component |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\base\Component |
className() | Returns the fully qualified name of this class. | yii\base\Object |
column() | Executes the query and returns the first column of the result. | yii\db\Query |
count() | Returns the number of records. | yii\db\Query |
create() | Creates a new Query object and copies its property values from an existing one. | yii\db\Query |
createCommand() | Creates a DB command that can be used to execute this query. | yii\db\ActiveQuery |
detachBehavior() | Detaches a behavior from the component. | yii\base\Component |
detachBehaviors() | Detaches all behaviors from the component. | yii\base\Component |
distinct() | Sets the value indicating whether to SELECT DISTINCT or not. | yii\db\Query |
each() | Starts a batch query and retrieves data row by row. | yii\db\Query |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\base\Component |
exists() | Returns a value indicating whether the query result contains any row of data. | yii\db\Query |
filterWhere() | Sets the WHERE part of the query but ignores empty operands. | yii\db\QueryTrait |
findFor() | Finds the related records for the specified primary record. | yii\db\ActiveRelationTrait |
findWith() | Finds records corresponding to one or multiple relations and populates them into the primary models. | yii\db\ActiveQueryTrait |
from() | Sets the FROM part of the query. | yii\db\Query |
getBehavior() | Returns the named behavior object. | yii\base\Component |
getBehaviors() | Returns all behaviors attached to this component. | yii\base\Component |
groupBy() | Sets the GROUP BY part of the query. | yii\db\Query |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\base\Component |
hasMethod() | Returns a value indicating whether a method is defined. | yii\base\Component |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\base\Component |
having() | Sets the HAVING part of the query. | yii\db\Query |
indexBy() | Sets the indexBy() property. | yii\db\QueryTrait |
init() | Initializes the object. | yii\db\ActiveQuery |
innerJoin() | Appends an INNER JOIN part to the query. | yii\db\Query |
innerJoinWith() | Inner joins with the specified relations. | yii\db\ActiveQuery |
inverseOf() | Sets the name of the relation that is the inverse of this relation. | yii\db\ActiveRelationTrait |
join() | Appends a JOIN part to the query. | yii\db\Query |
joinWith() | Joins with the specified relations. | yii\db\ActiveQuery |
leftJoin() | Appends a LEFT OUTER JOIN part to the query. | yii\db\Query |
limit() | Sets the LIMIT part of the query. | yii\db\QueryTrait |
max() | Returns the maximum of the specified column values. | yii\db\Query |
min() | Returns the minimum of the specified column values. | yii\db\Query |
off() | Detaches an existing event handler from this component. | yii\base\Component |
offset() | Sets the OFFSET part of the query. | yii\db\QueryTrait |
on() | Attaches an event handler to an event. | yii\base\Component |
onCondition() | Sets the ON condition for a relational query. | yii\db\ActiveQuery |
one() | Executes query and returns a single row of result. | yii\db\ActiveQuery |
orFilterWhere() | Adds an additional WHERE condition to the existing one but ignores empty operands. | yii\db\QueryTrait |
orHaving() | Adds an additional HAVING condition to the existing one. | yii\db\Query |
orOnCondition() | Adds an additional ON condition to the existing one. | yii\db\ActiveQuery |
orWhere() | Adds an additional WHERE condition to the existing one. | yii\db\QueryTrait |
orderBy() | Sets the ORDER BY part of the query. | yii\db\QueryTrait |
params() | Sets the parameters to be bound to the query. | yii\db\Query |
populate() | Converts the raw query results into the format as specified by this query. | yii\db\ActiveQuery |
populateRelation() | Finds the related records and populates them into the primary models. | yii\db\ActiveRelationTrait |
prepare() | Prepares for building SQL. | yii\db\ActiveQuery |
rightJoin() | Appends a RIGHT OUTER JOIN part to the query. | yii\db\Query |
scalar() | Returns the query result as a scalar value. | yii\db\Query |
select() | Sets the SELECT part of the query. | yii\db\Query |
sum() | Returns the sum of the specified column values. | yii\db\Query |
trigger() | Triggers an event. | yii\base\Component |
union() | Appends a SQL statement using UNION operator. | yii\db\Query |
via() | Specifies the relation associated with the junction table. | yii\db\ActiveRelationTrait |
viaTable() | Specifies the junction table for a relational query. | yii\db\ActiveQuery |
where() | Sets the WHERE part of the query. | yii\db\QueryTrait |
with() | Specifies the relations with which this query should be performed. | yii\db\ActiveQueryTrait |
Protected Methods
Method | Description | Defined By |
---|---|---|
filterCondition() | Removes empty operands from the given query condition. | yii\db\QueryTrait |
isEmpty() | Returns a value indicating whether the give value is "empty". | yii\db\QueryTrait |
normalizeOrderBy() | Normalizes format of ORDER BY data | yii\db\QueryTrait |
queryScalar() | Queries a scalar value by setting select() first. | yii\db\Query |
Events
Event | Type | Description | Defined By |
---|---|---|---|
EVENT_INIT | \yii\db\Event | An event that is triggered when the query is initialized via init(). | yii\db\ActiveQuery |
Property Details
A list of relations that this query should be joined with
The join condition to be used when this query is used in a relational context. The condition will be used in the ON part when yii\db\ActiveQuery::joinWith() is called. Otherwise, the condition will be used in the WHERE part of a query. Please refer to yii\db\Query::where() on how to specify this parameter.
See also onCondition().
The SQL statement to be executed for retrieving AR records. This is set by yii\db\ActiveRecord::findBySql().
Method Details
Constructor.
public void __construct ( $modelClass, $config = [] ) | ||
$modelClass | string | The model class associated with this query |
$config | array | Configurations to be applied to the newly created query object |
Executes query and returns all results as an array.
public array|yii\db\ActiveRecord[] all ( $db = null ) | ||
$db | \yii\db\Connection | The DB connection used to create the DB command. If null, the DB connection returned by $modelClass will be used. |
return | array|yii\db\ActiveRecord[] | The query results. If the query results in nothing, an empty array will be returned. |
---|
Adds an additional ON condition to the existing one.
The new condition and the existing one will be joined using the 'AND' operator.
See also:
public static andOnCondition ( $condition, $params = [] ) | ||
$condition | string|array | The new ON condition. Please refer to where() on how to specify this parameter. |
$params | array | The parameters (name => value) to be bound to the query. |
return | static | The query object itself |
---|
Creates a DB command that can be used to execute this query.
public \yii\db\Command createCommand ( $db = null ) | ||
$db | \yii\db\Connection | The DB connection used to create the DB command. If null, the DB connection returned by $modelClass will be used. |
return | \yii\db\Command | The created DB command instance. |
---|
Initializes the object.
This method is called at the end of the constructor. The default implementation will trigger an EVENT_INIT event. If you override this method, make sure you call the parent implementation at the end to ensure triggering of the event.
public void init ( ) |
Inner joins with the specified relations.
This is a shortcut method to joinWith() with the join type set as "INNER JOIN". Please refer to joinWith() for detailed usage of this method.
See also joinWith().
public static innerJoinWith ( $with, $eagerLoading = true ) | ||
$with | string|array | The relations to be joined with |
$eagerLoading | boolean|array | Whether to eager loading the relations |
return | static | The query object itself |
---|
Joins with the specified relations.
This method allows you to reuse existing relation definitions to perform JOIN queries. Based on the definition of the specified relation(s), the method will append one or multiple JOIN statements to the current query.
If the $eagerLoading
parameter is true, the method will also eager loading the specified relations,
which is equivalent to calling with() using the specified relations.
Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
This method differs from with() in that it will build up and execute a JOIN SQL statement
for the primary table. And when $eagerLoading
is true, it will call with() in addition with the specified relations.
public static joinWith ( $with, $eagerLoading = true, $joinType = 'LEFT JOIN' ) | ||
$with | string|array | The relations to be joined. Each array element represents a single relation. The array keys are relation names, and the array values are the corresponding anonymous functions that can be used to modify the relation queries on-the-fly. If a relation query does not need modification, you may use the relation name as the array value. Sub-relations can also be specified (see with()). For example,
|
$eagerLoading | boolean|array | Whether to eager load the relations specified in |
$joinType | string|array | The join type of the relations specified in |
return | static | The query object itself |
---|
Sets the ON condition for a relational query.
The condition will be used in the ON part when yii\db\ActiveQuery::joinWith() is called. Otherwise, the condition will be used in the WHERE part of a query.
Use this method to specify additional conditions when declaring a relation in the yii\db\ActiveRecord class:
public function getActiveUsers()
{
return $this->hasMany(User::className(), ['id' => 'user_id'])->onCondition(['active' => true]);
}
public static onCondition ( $condition, $params = [] ) | ||
$condition | string|array | The ON condition. Please refer to yii\db\Query::where() on how to specify this parameter. |
$params | array | The parameters (name => value) to be bound to the query. |
return | static | The query object itself |
---|
Executes query and returns a single row of result.
public yii\db\ActiveRecord|array|null one ( $db = null ) | ||
$db | \yii\db\Connection | The DB connection used to create the DB command. If null, the DB connection returned by $modelClass will be used. |
return | yii\db\ActiveRecord|array|null | A single row of query result. Depending on the setting of asArray(), the query result may be either an array or an ActiveRecord object. Null will be returned if the query results in nothing. |
---|
Adds an additional ON condition to the existing one.
The new condition and the existing one will be joined using the 'OR' operator.
See also:
public static orOnCondition ( $condition, $params = [] ) | ||
$condition | string|array | The new ON condition. Please refer to where() on how to specify this parameter. |
$params | array | The parameters (name => value) to be bound to the query. |
return | static | The query object itself |
---|
Converts the raw query results into the format as specified by this query.
This method is internally used to convert the data fetched from database into the format as required by this query.
public array populate ( $rows ) | ||
$rows | array | The raw query result from database |
return | array | The converted query result |
---|
Prepares for building SQL.
This method is called by \yii\db\QueryBuilder when it starts to build SQL from a query object. You may override this method to do some final preparation work when converting a query into a SQL statement.
public yii\db\Query prepare ( $builder ) | ||
$builder | \yii\db\QueryBuilder | |
return | yii\db\Query | A prepared query instance which will be used by \yii\db\QueryBuilder to build the SQL |
---|
Specifies the junction table for a relational query.
Use this method to specify a junction table when declaring a relation in the yii\db\ActiveRecord class:
public function getItems()
{
return $this->hasMany(Item::className(), ['id' => 'item_id'])
->viaTable('order_item', ['order_id' => 'id']);
}
See also via().
public static viaTable ( $tableName, $link, callable $callable = null ) | ||
$tableName | string | The name of the junction table. |
$link | array | The link between the junction table and the table associated with $primaryModel. The keys of the array represent the columns in the junction table, and the values represent the columns in the $primaryModel table. |
$callable | callable | A PHP callback for customizing the relation associated with the junction table.
Its signature should be |
Event Details
An event that is triggered when the query is initialized via init().